<!--
 * @Author: 谢陈洁
 * @Date: 2025-05-26 09:24:06
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-08-01 16:27:54
 * @Description: file content
-->
<template>
  <div class="page">
    <el-card class="table-card">
      <div class="action-box">
        <add-button v-permission="'user:add'" @click="openDialog()" type="primary">
          添加用户
        </add-button>
      </div>
      <ProTable
        :columns="columns"
        :data="dataList"
        :pagination="pagination"
        @pagination-change="handlePaginationChange"
        :loading="loading"
      >
        <template #action="{ row }">
          <edit-button size="small" v-permission="'user:edit'" @click="handleEdit(row)">
            编辑
          </edit-button>
          <del-button size="small" v-permission="'user:delete'" @click="handleDelete(row.id)">
            删除
          </del-button>
        </template>
      </ProTable>
    </el-card>
    <base-dialog
      v-model="dialogVisible"
      title="编辑用户"
      @cancel="closeDialog"
      width="700"
      @ok="handleSubmit"
    >
      <DynamicForm
        ref="formRef"
        :form-config="newFormConfig"
        @submit-success="handleSubmitSuccessBefore"
        v-model="formData"
        label-width="80px"
      />
    </base-dialog>
  </div>
</template>
<script setup lang="ts">
  import { getUserList, saveUserInfo, deleteUser } from '@/services/apis/system/user'
  import { columns, formConfig } from './config'
  import { useDeleteConfirm, useFormDialog, useOptions, useTableData } from '@/hooks'
  import { usePermissionStore } from '@/stores/permission'
  import { storeToRefs } from 'pinia'
  const permissionStore = usePermissionStore()
  const { fetchData, dataList, pagination, handlePaginationChange, loading } =
    useTableData(getUserList)
  const {
    dialogVisible,
    formData,
    formRef,
    openDialog,
    closeDialog,
    handleSubmit,
    handleSubmitSuccess
  } = useFormDialog(saveUserInfo, fetchData)
  const { generateOptions } = useOptions('roleIds')
  const { roles } = storeToRefs(permissionStore)
  const newFormConfig = computed(() => generateOptions(formConfig, roles.value))
  const { handleDelete } = useDeleteConfirm(deleteUser, fetchData)
  onMounted(() => {
    fetchData()
    permissionStore.getRoles()
  })
  const handleEdit = (row: any) => {
    openDialog({
      ...row,
      roleIds: row.roles.map((item: any) => item.id),
      avatar: row.avatar ? [{ url: row.avatar }] : []
    })
  }
  const handleSubmitSuccessBefore = (data: any) => {
    const formData = new FormData()
    for (const key in data) {
      if (key === 'avatar') {
        formData.append(key, data.avatar[0].raw || data.avatar[0].url)
      } else {
        formData.append(key, data[key])
      }
    }
    handleSubmitSuccess(formData)
  }
</script>
<style lang="scss" scoped></style>
